package com.baikeyang.app.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @className LimitRetryHashedMatcher
 * @description 重写匹配规则
 * Created by lenovo on 2018/7/12.
 */
public class LimitRetryHashedMatcher extends HashedCredentialsMatcher {

    //集群中可能会导致出现验证多过5次的现象，因为AtomicInteger只能保证单节点并发
    private Cache<String, AtomicInteger> passwordRetryCache;

    public LimitRetryHashedMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        // 当前登录用户名
        String username = (String)token.getPrincipal();
        //retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if(null == retryCount) {// 缓存中不存在
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if(retryCount.incrementAndGet() > 5) {// 重试次数达到上限
            System.err.println("username: " + username + " tried to login more than 5 times in period");
            //logger.warn("username: " + username + " tried to login more than 5 times in period");
            throw new ExcessiveAttemptsException("username: " + username + " tried to login more than 5 times in period");
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if(matches) {
            //clear retry data
            passwordRetryCache.remove(username);
        }
        return matches;



//        String username = (String)token.getPrincipal();
//    	Object elseement = EhCacheUtil.get(username);
//        Object element = 1;
//    	if(null == element) {
//    		EhCacheUtil.put(username, 1);
//    		element = 0;
//    	} else {
//    		element = Integer.valueOf(element.toString()) + 1;
//    		EhCacheUtil.put(username, element);
//    	}

//        AtomicInteger retryCount = new AtomicInteger(Integer.valueOf(element.toString()));
//
//        if(retryCount.incrementAndGet() > 3000) {
//            throw new AuthenticationException("登录错误次数达到上限，无法继续登录！");
//        }

//        boolean match =  super.doCredentialsMatch(token, info);
////    	if(match) {
////    		EhCacheUtil.remove(username);
////    	}
//        return match;
    }

}
